const axios = require('axios');
const key = "c0bca8256b659ef3845e1d44d701e830"
const {db} = require("../config/dbconfig");
const e = require("express");
const {IPinfoWrapper} = require("node-ipinfo");
const ipinfo = new IPinfoWrapper("ebe552a93c8225");

exports.getIPAddress = async (ip) => {
    const data = await axios
        .get(`https://restapi.amap.com/v3/ip?ip=${ip}&key=${key}`)
    return data.data
}
exports.saveIP = async (userIp, data) => {
    console.log("ipData", data);
    
    // 工具函数：处理字段，防止 undefined 或 []
    const sanitize = (val, defaultVal = '未知') => {
        if (Array.isArray(val) || val === undefined || val === null) return defaultVal;
        return val;
    }

    let inData = {
        ip_address: userIp,
        adcode: sanitize(data.adcode, 'NULL'),
        city: sanitize(data.city),
        info: sanitize(data.info, ''),
        infocode: sanitize(data.infocode, ''),
        province: sanitize(data.province),
        rectangle: sanitize(data.rectangle, ''),
        status: sanitize(data.status, '0'),
        country: "China",
    };

    console.log("inData", inData);

    // 如果城市为空，尝试获取国外 IP 信息
    if (inData.city === '未知') {
        try {
            const abroadData = await getIPAddressForAbroad(userIp);
            console.log("国外", abroadData);
            inData.city = sanitize(abroadData.city);
            inData.province = sanitize(abroadData.region);
            inData.country = sanitize(abroadData.country, 'Unknown');
            inData.rectangle = "NULL";
            inData.adcode = "NULL";
        } catch (e) {
            console.error("获取国外IP失败", e);
        }
    }

    const sql = `
        INSERT INTO ip_addresses 
        (ip_address, adcode, city, info, infocode, province, rectangle, status, country) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;

    return new Promise((resolve, reject) => {
        db.query(sql, [
            inData.ip_address,
            inData.adcode,
            inData.city,
            inData.info,
            inData.infocode,
            inData.province,
            inData.rectangle,
            inData.status,
            inData.country
        ], (err, result) => {
            if (err) {
                console.error("处理IP出错:", err);
                reject(err);
            } else {
                resolve(result);
            }
        });
    });
};

exports.ISIPAddress = async (ip) => {
    const sql = "SELECT COUNT(*) FROM ip_addresses WHERE ip_address=?"
    return new Promise((resolve, reject) => {
        db.query(sql, ip, (err, result) => {
            if (err) {
                reject(err);
            } else {
                resolve(result[0]['COUNT(*)']);
            }
        })
    })
}
exports.countIPAddress = async (ip) => {
    const sql = "UPDATE ip_addresses set count=count+1 where ip_address=?"
    return new Promise((resolve, reject) => {
        db.query(sql, ip, (err, result) => {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        })
    })
}


getIPAddressForAbroad = async (ip) => {
    return new Promise((resolve, reject) => {
        ipinfo.lookupIp(ip).then((res) => {
            resolve(res)
        })
    })
}